<!DOCTYPE html>
<html lang='en'>

<head>
    <meta charset='UTF-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0'>
    <title>Document</title>
    <script src='../vue.global.js'></script>
</head>

<body>
    <div id="app">
        <p>{{question}}</p>
        <p>
            Ask a yes/no question:
            <input v-model="question" />
        </p>
        <hr>
        <p>问题字数:{{questionLength}}</p>

        <p>{{ question }}:{{questionLength}}:{{questionLengthComputed}}</p>


        <p>{{ answer }}</p>
        <button @click="getAnswer">getAnswer</button>
    </div>

    <script>
        Vue.createApp({
            data(){
                return {
                    question:"我是一条龙吗",
                    answer:"五母鸡..."
                }
            },

            methods:{
                getAnswer(){
                    console.log("getAnswer");
                    this.answer = "容老夫想想..."

                    // fetch("https://yesno.wtf/api")
                    // .then(
                    //     response => response.json()
                    // ).then(
                    //     data=>{
                    //         this.answer = data.answer
                    //     }
                    // ).catch(
                    //     err=>this.answer=err
                    // )

                    setTimeout(() => {
                        this.answer = (Math.random() > 0.5 ? "yes" : "no")
                    }, 3000);
                    
                }
            },

            computed:{
                // 依赖的一首数据变化时 自动重新计算二手数据
                questionLength(){
                    return this.question.length
                }
            },

            watch:{
                // 监听question的数据变化 一旦数据变化回调以下函数
                // 入参为数据的最新值和数据的过去值
                question(newValue,oldValue){
                    console.log("question变化惹",newValue,oldValue);

                    /* 如果发现问题以?结尾 就立刻获取问题答案 */
                    if(this.question.endsWith("?")){
                        this.getAnswer()
                    }

                }
            }

        }).mount("#app")
    </script>
</body>

</html>